﻿using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Read.Api.Application.Commands.ProcessCommand;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Read.Api.Application.CommandsHander.ProcessCommandHandler
{
    public class GetProcessQueryCommandHandler : IRequestHandler<GetProcessQueryCommand, APIResult<APIPaging<Process>>>
    {
        private readonly ISqlSugarClient db;

        public GetProcessQueryCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<APIPaging<Process>>> Handle(GetProcessQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<Process>> result = new APIResult<APIPaging<Process>>();
            result.Code = APIEnum.success;
            result.Msg = "查询显示成功";
            var list = db.Queryable<Process>();

            if (!string.IsNullOrEmpty(request.ProcessName))
            {
                list = list.Where(p => p.ProcessName.Contains(request.ProcessName));
            }
            if (!string.IsNullOrEmpty(request.ProcessNumber))
            {
                list = list.Where(p => p.ProcessNumber == request.ProcessNumber);
            }
            if (!string.IsNullOrEmpty(request.ProcessType))
            {
                list = list.Where(p => p.ProcessType == request.ProcessType);
            }
            if (request.CapacityBody != null)
            {
                list = list.Where(p => p.CapacityBody == request.CapacityBody);
            }
            if (!string.IsNullOrEmpty(request.ProcessPerson))
            {
                list = list.Where(p => p.ProcessPerson == request.ProcessPerson);
            }
            if (!string.IsNullOrEmpty(request.DocumentMakers))
            {
                list = list.Where(p => p.DocumentMakers == request.DocumentMakers);
            }
            if (request.FriDocumentDate != null)
            {
                list = list.Where(p => p.DocumentDate >= request.FriDocumentDate);
            }
            if (request.EndDocumentDate != null)
            {
                list = list.Where(p => p.DocumentDate >= request.EndDocumentDate);
            }

            int TotalCount = list.Count();
            int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.ProcessId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<Process> paging = new APIPaging<Process>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.Data = paging;

            return await Task.FromResult(result);
        }
    }
}
